package cz.najman.emdroid.content;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;

import android.content.ContentValues;
import cz.najman.emdroid.mappings.Mappings;

public class SmartContentProducer implements ContentProducer {

	private Mappings mMappings;
	private ContentValues mData;	
	private String mRootTag, mStartTag;
	SimpleDateFormat mSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");

	public SmartContentProducer(Mappings mappingObject) {
		this.mMappings = mappingObject;
		mRootTag = mappingObject.ROOT_TAG;
	}

	@Override
	public void writeTo(OutputStream outstream) throws IOException {

		buildStringFromData(outstream);

	}

	private void buildStringFromData(OutputStream outstream) {

		try {
			TransformerFactory tf = TransformerFactory.newInstance();
			SAXTransformerFactory stf = (SAXTransformerFactory) tf;
			TransformerHandler th;
			th = stf.newTransformerHandler();
			th.setResult(new StreamResult(outstream));

			Map<String, String> map = mMappings.getFromDbMappings();

			Iterator<Entry<String, Object>> iterator = mData.valueSet().iterator();

			th.startDocument();
			mStartTag = map.get(Mappings.START_TAG);
			th.startElement("", "", mStartTag, null);
			while (iterator.hasNext()) {
				String dataKey = iterator.next().getKey();
				if (map.containsKey(dataKey)) {
					String data = mData.getAsString(dataKey);
					String xmlTag = map.get(dataKey);
					if(mMappings.getDates().contains(dataKey)){
						Long date = Long.parseLong(data);						
						data = mSdf.format(new Date(date));
					}
					th.startElement("", "", xmlTag, null);
					th.characters(data.toCharArray(), 0, data.length());
					th.endElement("", "", xmlTag);					
				}
			}
			th.endElement("", "", mStartTag);
			th.endDocument();

		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void setData(ContentValues data) {
		mData = data;
	}

	@Override
	public ContentValues getData() {
		return mData;
	}

	@Override
	public void setMappings(Mappings mappings) {
		mMappings = mappings;
		mRootTag = mappings.ROOT_TAG;
	}

}
